package cn.zh.service.impl;

import cn.zh.entity.User;
import cn.zh.service.MqSendService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.SimpleMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Random;
import java.util.UUID;

@Service
@Slf4j
public class MqSendServiceImpl implements MqSendService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void sendMsg(String str) {
        Message msg = new Message(str.getBytes());
        Message.addAllowedListPatterns(User.class.getName());
        //发送消息
        rabbitTemplate.send("MqSendService-One","Two",msg);
        //convertAndSend()方法会将不是Message的对象转为Message发送
        rabbitTemplate.convertAndSend("MqSendService-One","One",msg+"---One");
    }

    @Override
    public void sendDirectUser(User user) {
//        String s = JSON.toJSONString(user);
//        Message msg = new Message(s.getBytes(StandardCharsets.UTF_8));
//        msg.getMessageProperties().setExpiration("1000");
        SimpleMessageConverter simpleMessageConverter = new SimpleMessageConverter();
        Message message = simpleMessageConverter.toMessage(user, new MessageProperties());
        Message.addAllowedListPatterns(User.class.getName());
        System.out.println(message);
        rabbitTemplate.convertAndSend("MqSendService-One","dasdasdsad",message);
        //消息生产方设置消息确认，用于确认交换机和队列是否收到消息

        //rabbitTemplate.convertAndSend("MqSendService-One","Two",user+"---Two");
    }

    @Override
    public void sendRepeatDirectMsg(String str) {
        Message msg = new Message(str.getBytes(StandardCharsets.UTF_8));
        for (int i = 0; i < 20; i++) {
            rabbitTemplate.send("MqSendService-One","One",msg);
            rabbitTemplate.send("MqSendService-One","Two",msg);
        }
    }

    @Override
    public void sendFanoutMsg(String str) {
        Message msg = new Message(str.getBytes(StandardCharsets.UTF_8));
        for (int i = 0; i < 20; i++) {
            rabbitTemplate.send("Fanout-Ex",null,msg);
        }
    }

    @Override
    public void sendTopicMsg(String str) {
        Message msg = new Message(str.getBytes(StandardCharsets.UTF_8));
        for (int i = 0; i < 20; i++) {
            rabbitTemplate.send("Topic-Ex","One.Two.Three",msg);
        }
    }
}
